using System.Collections;
using System.Collections.Generic;
using System.Data;
using UnityEngine;
using UnityEngine.AI;

//先暂停, 不能用还是很复杂的
public class VActMotionVectorMechine
{
    public bool enable = true;
    public Transform transform;
    public VActProcessor processor;
    public NavMeshAgent agent;
    public VActMotionVectorMechine(VActProcessor processor, Transform transform)
    {
        this.processor = processor;
        this.transform = transform;
        agent = processor.gameObject.UniqueComponent<NavMeshAgent>();

        //就是这东西不好管理
        //难道order还要划分tick时序? 
        //还真有必要, 这里的mechineObserver就是得保证在Late队列中才能捕获到所有的输入
        mechineObserver = new()
        {
            complete = () => false,
            tick = Update,
            tickType = 1,
        };
        1f.Delay(() => mechineObserver.Subscribe()); // 这里先用时序做延后处理
    }
    public FuncObserver mechineObserver;
    public void Update()
    {
        if (frameCache.Equals(Vector3.zero)) return;
        transform.localPosition += frameCache;
        frameCache = Vector3.zero;
    }
    //还得定义衰减曲线和 冲击强度 ,  这里解耦出来具体逻辑 , 接下来看0向量抑制问题, 动画优先级到底在哪里 , 
    //这个内部调度应该考虑到速度的换算
    private Vector3 frameCache = Vector3.zero;
    public void PushMotionVector(float forward = 0, float right = 0, float up = 0)
    {

    }
    public void SetMotionVector(float forward = 0, float right = 0, float up = 0)
    {

    }


    public bool RandomSampleOnNavMesh(out Vector3 point, float minDistance = 2f, float maxDistance = 5f, int areaMask = NavMesh.AllAreas)
    {
        // 在 XZ 平面上采样随机方向
        Vector2 random2D = UnityEngine.Random.insideUnitCircle.normalized;
        float randomDistance = UnityEngine.Random.Range(minDistance, maxDistance);
        Vector3 randomDirection = new Vector3(random2D.x, 0f, random2D.y) * randomDistance;

        // 添加当前位置偏移
        Vector3 samplePosition = transform.position + randomDirection;

        NavMeshHit hit;
        // 使用随机距离作为采样半径更合理
        if (NavMesh.SamplePosition(samplePosition, out hit, randomDistance, areaMask))
        {
            point = hit.position;
            return true;
        }

        point = Vector3.zero;
        return false;
    }


    //这个地方得兼容navAgent , 冲刺等对地图的判定
    public void SetSpeed(float forward = 0, float right = 0, float up = 0)
    {
        forward *= Time.deltaTime;
        frameCache = new Vector3(right, up, forward);
    }


    public void Stop()
    {
        MotionVector = Vector3.zero;
    }

    public float maxSpeed = 1;
    //核心的向量部分
    public Vector3 _motionVector;
    public Vector3 MotionVector
    {
        get => _motionVector;
        set
        {
            if (value.magnitude >= maxSpeed)
            {
                _motionVector = Vector3.ClampMagnitude(value, maxSpeed);
                return;
            }
            _motionVector = value;
        }
    }

}
